import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:get/get.dart';
import 'package:note/common/common.dart';
import 'package:note/common/tools.dart';
import 'package:note/manager/global.dart';
import 'package:note/manager/localAuthUtil.dart';
import 'package:note/widgets/dialog.dart';
import '../../routeConfig.dart';
import 'state.dart';

class NoteInfoPageLogic extends GetxController {
  final NoteInfoPageState state = NoteInfoPageState();

  @override
  void dispose() {
    state.dispose();
    super.dispose();
  }

  void toEdit() {
    Get.toNamed(
      RouteConfig.editNotePage,
      arguments: state.note.value,
    )?.then((value) {
      state.note.update((val) {
        val = value;
      });
      if (state.note.value.images.length < state.swiperController.index + 1) {
        state.swiperController.move(value.images.length - 1, animation: false);
      }
    });
  }

  void toDelete() {
    GlobalUtil.deleteNote(state.note.value);
  }

  void onFavorite() {
    state.note.update((val) {
      val?.isFavorite = (!val.isFavorite);
      if (val?.isFavorite ?? false) {
        GlobalUtil.favoriteNum.value++;
      } else {
        GlobalUtil.favoriteNum.value--;
      }
    });
    //保存到本地
    GlobalUtil.setNote(state.note.value);
  }

  void onExport() {
    Get.dialog(defaultDialog(
        title: Strings.tip,
        content: '确定需要导出到本地文件夹吗？',
        sureFunction: () async {
          final directory = FilePath.getAppDirectory;
          String fileName =
              '${sanitizeFileName(state.note.value.title)}_${Random().nextInt(100)}.md';
          fileName = '$directory/$fileName';
          // 将文本内容转换为字节并保存到文件
          File(fileName).writeAsBytes(utf8.encode(state.note.value.data));
          Toasts.showToast('已保存到：$fileName');
        }));
  }

  String sanitizeFileName(String fileName) {
    final illegalChars = RegExp(r'[\\/:*?"<>|]');
    final sanitized = fileName.replaceAll(illegalChars, '_').trim();

    final spaceCharacter = RegExp(r'\s');
    final finalSanitized = sanitized.replaceAll(spaceCharacter, '');

    if (finalSanitized.endsWith('.')) {
      return finalSanitized.substring(0, finalSanitized.length - 1);
    }

    return finalSanitized;
  }

  void onLock() {
    Get.dialog(defaultDialog(
        content: state.note.value.isLocked ? '你确定要给该笔记解锁吗' : '你确定要给该笔记上锁吗？',
        sureFunction: () {
          LocalAuthUtil.instance.onUnlock().then((value) {
            if (value) {
              state.note.update((val) {
                val?.isLocked = (!val.isLocked);
              });
              //保存到本地
              GlobalUtil.setNote(state.note.value);
              Toasts.showToast(Strings.success);
            } else {
              Toasts.showToast(Strings.fail);
            }
          });
        }));
  }
}
